<template>
  <business-layout title='工单管理' custom-title>
    <template slot='header'>
      <div class='table-tab'>
        <a-tabs v-model='activeKey'>
          <a-tab-pane :key='0' tab='待指派' force-render>
          </a-tab-pane>
          <a-tab-pane :key='1' tab='待处理'>
          </a-tab-pane>
          <a-tab-pane :key='2' tab='待关单'>
          </a-tab-pane>
          <a-tab-pane :key='3' tab='已完成'>
          </a-tab-pane>
        </a-tabs>
      </div>
      <div class='table-operator'>
        <a-form :form='form' layout='inline' @submit='handleQueryData'>
          <!--          <a-form-item label='站点'>-->
          <!--            <a-select style='width: 200px;' placeholder='请选择站点' v-decorator="['stationDicId']"-->
          <!--                      :options='stationList'>-->
          <!--            </a-select>-->
          <!--          </a-form-item>-->
          <a-form-item label=''>
            <a-select style='width: 200px;'
                      :filterOption='filterOptionFun' allowClear :options='workOrderTypeList'
                      placeholder='请选择工单类型'
                      v-decorator="['typeDicId']">
            </a-select>
          </a-form-item>
          <a-form-item label=''>
            <a-select style='width: 200px;'
                      :filterOption='filterOptionFun' allowClear :options='userList' placeholder='请选择当前处理人'
                      v-decorator="['currUser']">
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type='primary' html-type='submit' style='margin-right: 10px'>
              <a-icon type='search' />
              查询
            </a-button>
            <a-button html-type='reset' style='margin-right: 10px' @click='handleResetData'>
              重置
            </a-button>
          </a-form-item>
          <a-form-item style='float: right'>
            <a-button type='primary' icon='plus' @click='handleAdd'>新建</a-button>
          </a-form-item>
        </a-form>
      </div>
    </template>

    <s-table
      ref='table'
      size='default'
      rowKey='id'
      :columns='columns'
      :data='loadData'
      showPagination='auto'
    >
      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='description' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>
      <span slot='handleDesc' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>
      <span slot='createdTime' slot-scope='text'>
        {{ text | dayjs }}
      </span>
      <span slot='confirmedTime' slot-scope='text'>
        <span v-if='text'>{{ text | dayjs }}</span>
        <span v-else></span>
      </span>

      <span slot='status' slot-scope='text'>
        <a-tag :color='text | filterStatusStyle'>
        {{ text | statusFilter }}
        </a-tag>
      </span>

      <span slot='action' slot-scope='text, record'>
        <template>
          <a @click='handleexamine(record)'>查看详情</a>
        </template>
        <!--        <template v-if='record.status === "1"'>-->
        <!--          <a-divider type='vertical' />-->
        <!--          <a @click='handleEdit(record)'>编辑</a>-->
        <!--        </template>-->
        <template v-if='record.status === "1" && computedCreatedUser(record)'>
          <a-divider type='vertical' />
          <a class='del-link' @click='handleCancelVisable(record)'>撤销</a>
        </template>
        <template v-if='record.status === "1" && computedCreatedUser(record)'>
          <a-divider type='vertical' />
          <a @click='handleDispatch(record)'>指派</a>
        </template>
        <template v-if='record.status === "2" && computedCurrUser(record)'>
          <a-divider type='vertical' />
          <a @click='handleHander(record)'>处理</a>
        </template>
        <template v-if='record.status === "3" && computedCreatedUser(record)'>
          <a-divider type='vertical' />
          <a @click='handleConfirmVisable(record)'>关单</a>
        </template>
      </span>
    </s-table>

    <create-work-order
      ref='createModal'
      :visible='visible'
      :loading='confirmLoading'
      :model='mdl'
      :edit='edit'
      @cancel='handleCancel'
      @ok='handleOk'
    />

    <dispatch-work-order
      ref='dispatchWorkOrder'
      :visible='dispatchWorkOrderVisible'
      :loading='dispatchWorkOrderLoading'
      @cancel='handleDispatchCancel'
      @ok='handleDispatchOk'
    />

    <handler-work-order
      ref='handlerWorkOrder'
      :visible='handlerWorkOrderVisible'
      :loading='handlerWorkOrderLoading'
      @cancel='handleHandlerCancel'
      @ok='handleHandlerOk'
    />
  </business-layout>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import {
  findToAssignWorkOrder,
  findToHandleWorkOrder,
  findToConfirmWorkOrder,
  findCompletedWorkOrder,
  assignWorkOrder,
  createWorkOrder,
  handleWorkOrder,
  confirmWorkOrder,
  cancelWorkOrder
} from '@/api/workerOrder'
import { findAllUserByPermissionCode } from '@/api/user'

import HandlerWorkOrder from './modules/HandlerWorkOrder.vue'
import DispatchWorkOrder from './modules/DispatchWorkOrder.vue'
import CreateWorkOrder from './modules/CreateWorkOrder.vue'
import { findDataDicInfoByType } from '@/api/dataDicInfo'
import { mapState } from 'vuex'

const columns = [
  {
    title: '编号',
    dataIndex: 'workorderNo'
  },
  {
    title: '工单描述',
    dataIndex: 'description',
    scopedSlots: { customRender: 'description' }
  },
  {
    title: '工单类型',
    dataIndex: 'type'
  },
  {
    title: '告警点',
    dataIndex: 'alarmPlace'
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '创建人',
    dataIndex: 'createdUser'
  },
  {
    title: '当前处理人',
    dataIndex: 'currUser'
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    scopedSlots: { customRender: 'createdTime' }
  },
  {
    title: '完成时间',
    dataIndex: 'confirmedTime',
    scopedSlots: { customRender: 'confirmedTime' }
  },
  {
    title: '备注',
    dataIndex: 'handleDesc',
    scopedSlots: { customRender: 'handleDesc' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'WorkOrder',
  components: {
    STable,
    Ellipsis,
    CreateWorkOrder,
    DispatchWorkOrder,
    HandlerWorkOrder
  },
  data() {
    this.columns = columns
    return {
      activeKey: 0,
      // create model
      visible: false,
      dispatchWorkOrderVisible: false,
      // 数据详情的id
      workOrderId: '',
      edit: true,
      workOrderTypeList: [],
      confirmLoading: false,
      dispatchWorkOrderLoading: false,
      handlerWorkOrderLoading: false,
      detailConfirmLoading: false,
      handlerWorkOrderVisible: false,
      form: this.$form.createForm(this),
      mdl: null,
      userList: [],
      // 高级搜索 展开/关闭
      advanced: false,
      mark: 0,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return this.getDataFun(requestParameters)
      },
      selectedRowKeys: [],
      selectedRows: [],
      stationList: []
    }
  },
  filters: {
    statusFilter(val) {
      const statusObj = {
        '1': '待指派',
        '2': '待处理',
        '3': '待关单',
        '4': '已撤销',
        '5': '已完成'
      }
      return statusObj[val]
    },
    filterStatusStyle(val) {
      if (+val === 1) {
        return 'cyan'
      }
      if (+val === 2) {
        return 'pink'
      }
      if (+val === 3) {
        return 'green'
      }
      if (+val === 4) {
        return 'orange'
      }
      if (+val === 5) {
        return 'blue'
      }
    }
  },
  created() {
    this.getTypeList()
    this.getUserList()
    if (this.$route.query.mark) {
      this.activeKey = 1
    }
  },
  computed: {
    ...mapState({
      username: state => state.user.info.username,
      userType: state => state.user.info.userType
    }),
    getDataFun() {
      if (+this.activeKey === 0) {
        return findToAssignWorkOrder
      }
      if (+this.activeKey === 1) {
        return findToHandleWorkOrder
      }
      if (+this.activeKey === 2) {
        return findToConfirmWorkOrder
      }
      if (+this.activeKey === 3) {
        return findCompletedWorkOrder
      }
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  watch: {
    activeKey() {
      this.$refs.table.refresh()
    }
  },
  methods: {
    computedCurrUser(value) {
      // 管理员
      if (this.userType === '1') {
        return true
      }
      if (value.currUser === this.username) {
        return true
      }
      return false
    },
    computedCreatedUser(value) {
      // 管理员
      if (this.userType === '1') {
        return true
      }
      if (value.createdUser === this.username) {
        return true
      }
      return false
    },
    handleResetData() {
      this.queryParam = {}
      this.form.resetFields()
      this.$refs.table.refresh()
    },
    handleDispatch(value) {
      this.dispatchWorkOrderVisible = true
      this.workOrderId = value.id
    },
    handleHander(value) {
      this.handlerWorkOrderVisible = true
      this.workOrderId = value.id
    },
    handleCancelVisable(value) {
      const that = this
      this.$confirm({
        title: '警告',
        content: '当前操作不可逆、是否继续？',
        async onOk() {
          cancelWorkOrder({
            workorderId: value.id
          }).then(res => {
            that.$message.success('更新成功！')
            that.$refs.table.refresh()
          })
        }
      })
    },
    handleConfirmVisable(value) {
      const that = this
      this.$confirm({
        title: '警告',
        content: '确定当前工单是否完成?并直接关闭么？',
        async onOk() {
          confirmWorkOrder({
            workorderId: value.id
          }).then(res => {
            that.$message.success('更新成功！')
            that.$refs.table.refresh()
          })
        }
      })
    },
    filterOptionFun(inputValue, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
      )
    },
    getUserList() {
      findAllUserByPermissionCode({ pageNum: 1, pageSize: 999, permissionCode: 'yunweiguanli' }).then(res => {
        this.userList = res.map(item => {
          return {
            ...item,
            key: item.id,
            label: item.username
          }
        })
      })
    },
    getStationList() {
      findDataDicInfoByType(13).then(res => {
        console.log(res)
        this.stationList = res.map(item => {
          return {
            ...item,
            key: item.code,
            label: item.name
          }
        })
      })
    },
    getTypeList() {
      findDataDicInfoByType(12).then(res => {
        this.workOrderTypeList = res.map(item => {
          return {
            ...item,
            key: item.id,
            label: item.name
          }
        })
      })
    },
    handleexamine(record) {
      this.visible = true
      this.mdl = { ...record }
      this.edit = false
    },
    handleAdd() {
      this.$refs.createModal.imageUrl = null
      this.mdl = null
      this.edit = true
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.edit = true
      this.mdl = { ...record }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values && values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              setTimeout(() => {
                resolve()
              }, 1000)
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('更新成功')
            })
          } else {
            // 新增
            createWorkOrder(values).then(res => {
              this.visible = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('新增成功')
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleDispatchOk() {
      const form = this.$refs.dispatchWorkOrder.form
      const that = this
      this.dispatchWorkOrderLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 新增
          assignWorkOrder({
            ...values,
            desc: values.desc || '',
            workorderId: that.workOrderId
          }).then(res => {
            this.dispatchWorkOrderVisible = false
            // 重置表单数据
            form.resetFields()
            // 刷新表格
            this.$refs.table.refresh()

            this.$message.success('更新成功')
          }).finally(() => {
            this.dispatchWorkOrderLoading = false
          })
        } else {
          this.dispatchWorkOrderLoading = false
        }
      })
    },
    handleHandlerOk() {
      const form = this.$refs.handlerWorkOrder.form
      const that = this
      this.handlerWorkOrderLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 新增
          handleWorkOrder({
            ...values,
            workorderId: that.workOrderId
          }).then(res => {
            that.handleWorkOrderVisible = false
            // 重置表单数据
            form.resetFields()
            // 刷新表格
            this.$refs.table.refresh()
            this.handlerWorkOrderVisible = false
            this.$message.success('更新成功')
          }).finally(() => {
            this.handlerWorkOrderLoading = false
          })
        } else {
          this.handlerWorkOrderLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleDispatchCancel() {
      this.dispatchWorkOrderVisible = false
      const form = this.$refs.dispatchWorkOrder.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleHandlerCancel() {
      this.handlerWorkOrderVisible = false
      const form = this.$refs.handlerWorkOrder.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleQueryData(e) {
      e.preventDefault()
      const form = this.form
      const that = this
      const queryObj = {}
      form.validateFields((error, values) => {
        Object.keys(values).forEach(key => {
          if (values[key]) {
            queryObj[key] = values[key]
          }
        })
        this.queryParam = queryObj
        that.$refs.table.refresh()
      })
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style lang='less' scoped>
.table-tab {

}
</style>

